﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Library;
using System.IO;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
using SautinSoft;
using BCL.easyPDF6.Interop.EasyPDFPrinter;
namespace QuanLyThi
{
    public partial class FrmInDeThi : Form
    {
        public static string mConnect = FrmMain.mConnect;
        private string msql = "";
        public DGC_Library mLibrary = new DGC_Library(mConnect);

        int id_MaDeThi = 0;
        int Ms_Mondaotao = 0;
        public FrmInDeThi(int id_MaDeThi, int Ms_Mondaotao)
        {
            InitializeComponent();
            this.id_MaDeThi = id_MaDeThi;
            this.Ms_Mondaotao = Ms_Mondaotao;
            this.LoadMauDe();
            XuatRTF();
        }

        private void LoadMauDe()
        {
         
                msql = "select * from MauDeThi where MS_Mondaotao=" + Ms_Mondaotao;
                DataTable dt = mLibrary.GetDataTable(msql, "a");
                //DataRow newRow = dt.NewRow();
                //newRow["ID"] = "0";
                //newRow["TenMau"] = "Không chọn mẩu";
                //dt.Rows.Add(newRow);
                cboMauDeThi.DataSource = dt;
                cboMauDeThi.DisplayMember = "TenMau";
                cboMauDeThi.ValueMember = "ID";
                //cboMauDeThi.SelectedValue = "0";
           
         

        }





        int IDCauHoiChaTmp = 0;
        void XuatRTF()
        {
            msql = "select * from tb_MaDeChiTiet where id_MaDeThi=" + id_MaDeThi + " order by idMaDeChiTiet,CauHoiCha,IDCauHoiCha";
            DataTable dt = mLibrary.GetDataTable(msql, "Dethi");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    bool CauHoiCha = false;
                    if (bool.Parse(dt.Rows[i]["CauHoiCha"].ToString()))//TRue
                    {
                        int IDCauHoiCha = int.Parse(dt.Rows[i]["IDCauHoiCha"].ToString());
                       
                        if (IDCauHoiChaTmp != IDCauHoiCha)//khac nhau thi insert
                        {
                            msql = "  select * from tb_CauHoiCha where IDCauHoiCha=" + IDCauHoiCha;
                            DataTable dtCauHoiCha = mLibrary.GetDataTable(msql, "CauHoi");
                            //Duyet cAu hoi cha xuat ra Richtextbox
                            if (dt.Rows.Count > 0)
                            {

                               
                                this.Insert1CauHoi(noidung, dtCauHoiCha, i, 0, true, false, 0,false);
                            }
                        }
                        //Set ben tmp
                        IDCauHoiChaTmp = IDCauHoiCha;



                        //Duyet cau hoi con
                        int cauhoiid_ = int.Parse(dt.Rows[i]["CauHoi"].ToString());
                        msql = "  select * from dbo.tb_Nganhangdethi where Cauhoi=" + cauhoiid_ + "  and Ms_Mondaotao=" + Ms_Mondaotao + " order by CauhoiId";
                        DataTable dtCauHoi_ = mLibrary.GetDataTable(msql, "CauHoi");
                        //Duyet cAu hoi xuat ra Richtextbox
                        for (int k = 0; k < dtCauHoi_.Rows.Count; k++)
                        {
                            bool isCau = false;
                            if (k == 0) isCau = true;

                            bool motdapan = false;
                            if (dtCauHoi_.Rows[k]["TTCauHoi"].ToString() == "0") motdapan = true;
                            this.Insert1CauHoi(noidung, dtCauHoi_, i, k, isCau, true, k, motdapan);
                        }
                       
                    }
                    else//khong co cau hoi cha
                    {
                        int cauhoiid = int.Parse(dt.Rows[i]["CauHoi"].ToString());
                        msql = "  select * from dbo.tb_Nganhangdethi where Cauhoi=" + cauhoiid + "  and Ms_Mondaotao=" + Ms_Mondaotao + " order by CauhoiId";
                        DataTable dtCauHoi = mLibrary.GetDataTable(msql, "CauHoi");
                        //Duyet cAu hoi xuat ra Richtextbox
                        for (int k = 0; k < dtCauHoi.Rows.Count; k++)
                        {                           
                            bool isCau=false;
                            if(k==0) isCau=true;

                            bool motdapan = false;
                            if (dtCauHoi.Rows[k]["TTCauHoi"].ToString() == "0") motdapan = true;
                            this.Insert1CauHoi(noidung, dtCauHoi, i, k, isCau, false, 0, motdapan);
                        }


                    }

                  
                }
            }

        }
        private void LoadNoidung(RichTextBox rt, byte[] noidung)
        {
            Stream theFile = new MemoryStream(noidung);
            rt.LoadFile(theFile, RichTextBoxStreamType.RichText);
        }

        private void Insert1CauHoi(RichTextBox rt, DataTable dtNguon, int vitricau,int vitridapan,bool isCau,bool isCauHoiCon,int vitricauhoicon,bool motdapan)
        {
            RichTextBox rtTmp = new RichTextBox();
            byte[] noidung = (byte[])dtNguon.Rows[vitridapan]["noidung"];


            Stream theFile = new MemoryStream(noidung);
            rtTmp.LoadFile(theFile, RichTextBoxStreamType.RichText);


           
            //insert vao dau mloi cau hoi           
           
            if (isCau)
            {
                rtTmp.Select(0, 0);
                if (isCauHoiCon)
                    Clipboard.SetText("Câu " + (vitricau + 1).ToString() +"."+ (vitricauhoicon + 1).ToString() + ":  ");
                else
                    Clipboard.SetText("Câu " + (vitricau + 1).ToString() + ":  ");
                rtTmp.Paste();
            }
            else
            {


                //msql = "  select * from TuyChon ";
                //DataTable dtdapan = mLibrary.GetDataTable(msql, "dd");
                //RichTextBox rtTuyChon = new RichTextBox();
                //byte[] btuychon = null;

                //if (motdapan)
                //{
                //    btuychon = (byte[])dtdapan.Rows[1]["Tuychon"];
                //    Stream theFileTC = new MemoryStream(btuychon);
                //    rtTuyChon.LoadFile(theFileTC, RichTextBoxStreamType.RichText);
                //    Clipboard..SetText("O");
                //}
               



                ////
                rtTmp.Select(0, 0);
                string dapan = "";
                if (vitridapan == 1) dapan = "a. ";
                else if (vitridapan == 2) dapan = "b. ";
                else if (vitridapan == 3) dapan = "c. ";
                else if (vitridapan == 4) dapan = "d. ";
                else if (vitridapan == 5) dapan = "e. ";
                else if (vitridapan == 6) dapan = "f. ";
                else if (vitridapan == 7) dapan = "g. ";
                else if (vitridapan == 8) dapan = "h. ";
                else if (vitridapan == 9) dapan = "i. ";
                else dapan = "Cuối cùng :";
            

                Clipboard.SetText(dapan);
                rtTmp.Paste();


                //Insert kieu dap an
                rtTmp.Select(0, 0);
                if (motdapan)
                    Clipboard.SetText("O ");
                else
                    Clipboard.SetText("□ ");
                rtTmp.Paste();
            }
          




            //insert newline
            rt.AppendText("\n");
            rt.SelectedRtf = rtTmp.Rtf;
            
        }

        private void butthoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void butthem_Click(object sender, EventArgs e)
        {
            this.SaveMyFile();
           
        }

        public void SaveMyFile()
        {
            // Create a SaveFileDialog to request a path and file name to save to.
            SaveFileDialog saveFile1 = new SaveFileDialog();

            // Initialize the SaveFileDialog to specify the RTF extension for the file.
            saveFile1.DefaultExt = "*.rtf";
            saveFile1.Filter = "RTF Files|*.rtf";

            // Determine if the user selected a file name from the saveFileDialog.
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
               saveFile1.FileName.Length > 0)
            {
                // Save the contents of the RichTextBox into the file.
                noidung.SaveFile(saveFile1.FileName, RichTextBoxStreamType.RichText);
            }
        }

        private void PrintPDF()
        {
            PdfMetamorphosis   p = new PdfMetamorphosis();
            
            //this property is necessary only for registered version
            //p.Serial = "XXXXXXXXXXX";

            //specify some options
            p.PageStyle.PageOrientation.Landscape();
            //specify header in HTML format
            //p.Header.Html("<b>Sample header in HTML format</b>");

            //specify footer in RTF format
            //p.Footer.Rtf("{\b Bold footer}");
          

            //specify page numbers
            p.PageStyle.PageNumFormat = "Page {page} of {numpages}";

            if (p != null)
            {
                InPdf(p);
            }

           
        }

        void InPdf(PdfMetamorphosis p)
        {
            // Create a SaveFileDialog to request a path and file name to save to.
            SaveFileDialog saveFile1 = new SaveFileDialog();

            // Initialize the SaveFileDialog to specify the RTF extension for the file.
            saveFile1.DefaultExt = "*.rtf";
            saveFile1.Filter = "PDF Files|*.pdf";

            // Determine if the user selected a file name from the saveFileDialog.
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
               saveFile1.FileName.Length > 0)
            {
                // Save the contents of the RichTextBox into the file.
                noidung.SaveFile(Application.StartupPath + "\\test.rtf", RichTextBoxStreamType.RichText);
            }


            string rtfPath = Application.StartupPath + "\\test.rtf";
            string pdfPath = saveFile1.FileName;

            int i = p.RtfToPdfConvertFile(rtfPath, pdfPath);

            if (i == 0)
            {
                System.Diagnostics.Process.Start(pdfPath);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
          
            this.ConvertToPDF();
        }




        private void ConvertToPDF()
        {
            Printer oPrinter = null;
            PrintJob oPrintJob = null;

            Type type = Type.GetTypeFromProgID("easyPDF.Printer.6");
            oPrinter = (Printer)Activator.CreateInstance(type);

            oPrintJob = oPrinter.PrintJob;



            // Create a SaveFileDialog to request a path and file name to save to.
            SaveFileDialog saveFile1 = new SaveFileDialog();

            // Initialize the SaveFileDialog to specify the RTF extension for the file.
            saveFile1.DefaultExt = "*.rtf";
            saveFile1.Filter = "PDF Files|*.pdf";

            // Determine if the user selected a file name from the saveFileDialog.
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
               saveFile1.FileName.Length > 0)
            {
                // Save the contents of the RichTextBox into the file.
                noidung.SaveFile(Application.StartupPath + "\\test.rtf", RichTextBoxStreamType.RichText);
            }


            string rtfPath = Application.StartupPath + "\\test.rtf";
            string pdfPath = saveFile1.FileName;


            oPrintJob.PrintOut(rtfPath, pdfPath);


              
        }

        private void butXemMau_Click(object sender, EventArgs e)
        {
            if (int.Parse(cboMauDeThi.SelectedValue.ToString()) != 0)
            {
                FrmXemMauDeThi FRM = new FrmXemMauDeThi(int.Parse(cboMauDeThi.SelectedValue.ToString()));
                FRM.ShowDialog();
            }
            else
            {
                MessageBox.Show("Vui lòng chọn mẩu cần xem", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void chkapdung_CheckedChanged(object sender, EventArgs e)
        {
            if (chkapdung.Checked)
            {
                noidung.Clear();
                this.ApDungMauHeader(noidung,this.getSource(int.Parse(cboMauDeThi.SelectedValue.ToString())));
                this.XuatRTF();
                this.ApDungMauFooter(noidung, this.getSource(int.Parse(cboMauDeThi.SelectedValue.ToString())));
            }
            else
            {
                noidung.Clear();
                this.XuatRTF();
            }
        }
        DataTable getSource(int ID)
        {
            DataTable dtH=null;
            msql = "SELECT*  FROM [dbo].[MauDeThi] " +
                             " WHERE ID=" + ID;
            dtH = mLibrary.GetDataTable(msql, "a");
            return dtH;
        }

        private void ApDungMauHeader(RichTextBox rt, DataTable dtNguon)
        {
            //HEADER
            RichTextBox rtNoiDungHeader = new RichTextBox();
            byte[] NoiDungHeader = (byte[])dtNguon.Rows[0]["NoiDungHeader"];
            Stream theFile = new MemoryStream(NoiDungHeader);
            rtNoiDungHeader.LoadFile(theFile, RichTextBoxStreamType.RichText);
          
            rt.SelectedRtf = rtNoiDungHeader.Rtf;

        }
        private void ApDungMauFooter(RichTextBox rt, DataTable dtNguon)
        {           

            //FOOTER
            RichTextBox rtNoiDungFooter = new RichTextBox();
            byte[] NoiDungFooter = (byte[])dtNguon.Rows[0]["NoiDungFooter"];
            Stream theFile1 = new MemoryStream(NoiDungFooter);
            rtNoiDungFooter.LoadFile(theFile1, RichTextBoxStreamType.RichText);

            rt.SelectedRtf = rtNoiDungFooter.Rtf;

        }

        private void cboMauDeThi_SelectionChangeCommitted(object sender, EventArgs e)
        {
            chkapdung_CheckedChanged(null, null);
        }





    }
}
